<template>
  <div class="newWindow">
    <div class="conten">
      <div class="T-title flexBetween">
        <!-- <h4 > 电站建设1/3</h4> -->
        <div class="title-l">
          <div :class="{ 'title-l-s': true, active: tabIndex == -1 }" @click="tabClick(-1, '')">
            {{ $t('licence.sys_all') }}
          </div>
          <div v-for="(item, index) in GatewayList" :key="index" class="title-l-s"
            :class="{ 'title-l-s': true, active: tabIndex == index }" @click="tabClick(index, item)">
            {{ item.gatewayName }}
            <span class="color1" v-if="item.whiteList == 0">{{
              $t('licence.gat_whiteList0') }}</span>
            <span class="color2" v-if="item.whiteList == 1">{{
              $t('licence.gat_whiteList1') }}</span>
            <span class="color3" v-if="item.whiteList == 2">{{
              $t('licence.gat_whiteList2') }}</span>
            <span class="color4" v-if="item.whiteList == 3">{{
              $t('licence.gat_whiteList3') }}</span>
          </div>
        </div>
        <el-row class="button">
          <el-dropdown @command="handleCommand" v-if="env == 'staging'">
            <!-- <span class="el-dropdown-link">
              批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span> -->
            <el-button type="primary">
              批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="addAll">一键添加网关和逆变器</el-dropdown-item>
                <el-dropdown-item command="delAll">一键删除网关和逆变器</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="primary" plain @click="addShow">{{
            $t('licence.gat_addGateway') }}</el-button>
          <el-button type="primary" @click="distributionNetworks" plain>{{
            $t('licence.gat_peiwang') }}</el-button>
          <el-button type="primary" v-if="tabIndex != -1" plain @click="editShow">{{ $t('licence.gat_bianjiGateway')}}</el-button>
        </el-row>
      </div>
      <!-- 添加设备按钮 -->
      <div class="content">
        <el-button type="primary" style="margin: 20px 0" @click="addS">{{
          $t('licence.gat_addS') }}</el-button>
        <el-button type="primary" v-if="inverterList.length&&canDel&&env == 'staging'" @click="delAllInveters(gateway)">{{$t('licence.delAll')}}</el-button>
        <!-- 根据num动态切换显示div内容 -->
        <div>
          <el-table :data="inverterList" style="width: 100%; margin-top: 24px" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{textAlign: 'center',background: '#F6F8FA',}">
            <el-table-column prop="gatewayName" :label="$t('licence.gat_gatewayName')">
            </el-table-column>
            <el-table-column prop="lable" :label="$t('licence.gat_lable')">
            </el-table-column>
            <el-table-column prop="state" :label="$t('licence.sys_status')">
              <template>
                <el-button type="text" size="small" style="color: #0e1319">{{$t('licence.gat_state') }}</el-button>
              </template>
            </el-table-column>
            <el-table-column :label="$t('licence.fau_operation')">
              <template #default="scope">
                <el-button @click="unbound(scope.row)" type="text" size="small" style="color: #305add">{{
                  $t('licence.gat_unbound') }}</el-button>
                <el-button @click="del(scope.row)" type="text" size="small" style="color: #ff2d2d">{{ $t('licence.del')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="Button">
          <el-button @click="resetForm">{{ $t('licence.upperStep') }}</el-button>
          <el-button type="primary" @click="submitForm">{{
            $t('licence.determine') }}</el-button>
        </div>
        <!-- 新增/编辑网关弹框 -->
        <el-dialog center :title="dialogTitle" v-model="dialogGateway">
          <el-form :model="gatewayForm" label-position="top">
            <el-form-item :label="$t('licence.gat_gatewayName')">
              <el-input v-model="gatewayForm.gatewayName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('licence.gat_lableGateway')">
              <el-input v-model="gatewayForm.lable" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogGateway = false">{{
              $t('licence.cancel') }}</el-button>
            <el-button type="primary" @click="addGateway">{{
              $t('licence.determine') }}</el-button>
            <el-button type="danger" @click="delGateway">{{
              $t('licence.del') }}</el-button>
          </div>
        </el-dialog>
        <!-- 添加设备弹框 -->
        <el-dialog :title="title" v-model="dialogEquipment">
          <div style="margin-bottom: 20px">
            <el-input v-model="EquipmentData.lable" :placeholder="$t('licence.gat_shulable')"
              style="width: 350px; margin-right: 10px"></el-input>
            <el-button type="primary" @click="addEquipment">{{
              $t('licence.gat_addEquipment') }}</el-button>
          </div>
          <el-table :data="EquipmentData" border style="width: 100%">
            <el-table-column prop="lable" :label="$t('licence.gat_shebei')" width="350">
            </el-table-column>
            <el-table-column prop="operation" :label="$t('licence.fau_operation')">
              <template #default="scope">
                <el-button type="text" style="color: #305add" @click="addInverter(scope.row)">{{ $t('licence.gat_state')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>
      </div>
       <!-- 添加设备失败弹框 -->
      <el-dialog :title="$t('licence.get_reason')" v-model="dialogReason" width="50%">
        <div style="margin-bottom: 20px">
          <el-button type="success">{{ $t('licence.success ') }}：{{ lulu.success }}</el-button>
          <el-button type="info">{{ $t('licence. Fail ') }}：{{ lulu.failed }}</el-button>
        </div>
        <el-table :data="reasonData" border style="width: 100%">
          <el-table-column align="center" prop="lable" :label="$t('licence.gat_lable')">
          </el-table-column>
          <el-table-column align="center" prop="reason" :label="$t('licence.get_shibai')">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogReason = false">{{
            $t('licence.determine') }}</el-button>
        </span>
      </el-dialog>
       <!-- 一键添加网关和逆变器 -->
       <el-dialog title="一键添加网关和逆变器" v-model="addAll" width="50%">
        <el-form :model="oneTapGatewayList" ref="oneTapAddRef" label-position="top">
            <el-form-item label="网关标签">
              <el-input type="textarea" :rows="5" v-model="oneTapGatewayList.lable" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="逆变器标签">
              <el-input type="textarea" :rows="5" v-model="oneTapGatewayList.psLabel" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addAll = false">取消</el-button>
            <el-button type="primary" @click="addAllGatewayListByOneTap">添加</el-button>
        </span>
      </el-dialog>
      <el-dialog title="失败的网关和逆变器" v-model="addAllError" width="50%">
        <el-table :data="addAllErrorList" style="width: 100%; margin-top: 24px" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{textAlign: 'center',background: '#F6F8FA',}">
            <el-table-column label="失败的标签">
              <template #default="scope">
                <div>{{ scope.row }}</div>
              </template>
            </el-table-column>
          </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addAllError = false">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts" name="GatewayList">
import { addGateways, getGatewayLists, editorGateway, delGateways,delAllInveter, addPs, getDindingInverter, getDindingInverterS,oneTapAddAllGateway,oneTapDelAllGateway, unboundDel, distributionNetwork, } from "@/api/dianzhan/gatewayList";
import { paramDelivery } from "@/api/dianzhan/parameter";
const env = import.meta.env.VITE_APP_ENV
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const dialogReason = ref(false) //设备失败弹框
const reasonData = ref([])
const lulu = ref({
  success: '',
  failed: '',
})
// 添加设备弹框标题
const title = ref(t("licence.gat_title"))
const nameSn = ref('') //弹框名称
const electricId = ref(0)//单个电站id
const tabIndex = ref(-1)
const GatewayList = ref([{
  gatewayName: '',
  whiteList: -1,
}]) //网关列表
const gateway = ref(undefined) //网关单个
const canDel = computed(() => typeof gateway.value!=='undefined');
const dialogTitle = ref(t("licence.gat_addGateway"))
const dialogEquipment = ref(false) //添加设备
const dialogGateway = ref(false) //新增/编辑网关
const oneTapAddRef = ref()
// 网关表单
const gatewayForm = ref(
  {
    lable: '',
    gatewayName: ''
  }
)
// 一件添加网关表单
const oneTapGatewayList = ref(
  {
    lable: '',
    psLabel:''
  }
)
const lable = ref('') //输入逆变器添加
//网关下逆变器列表
const inverterList = ref([])
// 未绑定的逆变器
const EquipmentData = ref([
  {
    lable: '',
  }
])
const lang = ref<string | number>('')
const route = useRoute()
const router = useRouter()
const labelList = ref('')
const psLabelList = ref('')
const addAll = ref(false)
const addAllError = ref(false)
const addAllErrorList = ref([])
onMounted(() => {
  electricId.value = route.query.id; //单个电站id
  // 获取语言
  if (localStorage.getItem("locale") == "en_US") {
    lang.value = 1;
  } else {
    lang.value = 0;
  }
  if(!electricId.value) return ElMessage.error(t("licence.gat_selectStation"));
  // 获取网关列表
  getGatewayList();
  //获取网关下绑定逆变器列表
  tabClick(-1, '');
})
// 配网
const distributionNetworks = async () => {
  if (!gateway.value) {
    ElMessage.error(t("licence.gat_gateway"));
    return;
  } else {
    await distributionNetwork({
      stationId: electricId.value,
      gatId: gateway.value.id,
    });
    ElMessage.success(t("licence.success"));
  }
}

const handleCommand =  (command: string | number | object) => {
  if(command == 'addAll'){
    addAll.value  = true
  }
  else if(command == 'delAll'){
    addDelGatewayListByOneTap()
  }
}
const addAllGatewayListByOneTap = async () =>{
  let data = {
      lable: oneTapGatewayList.value.lable,
      psLabel: oneTapGatewayList.value.psLabel,
      stationId: electricId.value,
    };
    await oneTapAddAllGateway(data).then(res=>{
      //大于0成功，-1:网关标签不能重复，-2:逆变器标签不能重复，
      //-3:网关标签与SN不匹配，-4:网关标签已被绑定，-5:逆变器标签与SN不匹配，-6:逆变器标签已被绑定
        if(res.data.resultCode<=0){
          addAllError.value=true
          addAllErrorList.value=res.data.resultList
          if(res.data.resultCode==-1){
            ElMessage.error('网关标签不能重复');
            return
          }else if(res.data.resultCode==-2){
            ElMessage.error('逆变器标签不能重复');
            return
          }else if(res.data.resultCode==-3){
            ElMessage.error('网关标签与SN不匹配');
            return
          }else if(res.data.resultCode==-4){
            ElMessage.error('网关标签已被绑定');
            return
        }
      }else{
        addAll.value=false
        tabClick(-1, '');
        ElMessage.success('添加成功');
      }

      oneTapAddRef.value?.resetFields();
    }).catch(e=>{
      ElMessage.error(e.msg);
    })
}
const addDelGatewayListByOneTap = async () =>{
  let params = {
      stationId: electricId.value,
    };
    await oneTapDelAllGateway(params).then(res=>{
        if(res.data<=0){
          ElMessage.error('删除失败');
      }else{
        addAllError.value=false
        tabClick(-1, '');
        ElMessage.success('删除成功');
      }

      oneTapAddRef.value?.resetFields();
    }).catch(e=>{
      ElMessage.error(e.msg);
    })
}
// 添加设备 新增逆变器
const addS = async () => {
  if (!gateway.value) {
    ElMessage.error(t("licence.gat_gateway"));
    return;
  } else {
    dialogEquipment.value = true;
    nameSn.value = title.value + "(" + gateway.value.lable + ")";
    let query = {
      id: electricId.value,
      flag: "1",
    };
    let res = await getDindingInverterS(query);
    EquipmentData.value = res.data;
    // await ElMessage.success(t("licence.success"));
  }
}
//新增逆变器
const addEquipment = async () => {
  let data = {
    lable: EquipmentData.value.lable,
    gatId: gateway.value.id,
    // remark: "",
  };
  let res = await addPs(data);
  reasonData.value = res.data.reasonList;
  lulu.value = res.data;
  // await ElMessage.success(t("licence.success"));
  dialogReason.value = true;
  lable.value = "";
  dialogEquipment.value = false;
  tabClick(-1, '');
}
// 绑定逆变器
const addInverter = async (tab: any) => {
  let data = {
    lable: tab.lable,
    gatId: gateway.value.id,
  };
  await addPs(data);
  await ElMessage.success(t("licence.success"));
  lable.value = "";
  dialogEquipment.value = false;
  tabClick(-1, '');
}
// tab网关切换
// 获取电站/网关下已绑定的逆变器
const tabClick = async (index: any, item: any) => {
  tabIndex.value = index;
  gateway.value = item;
  if (gateway.value) {
    // 网关下逆变器
    let res = await getDindingInverter(gateway.value.id);
    inverterList.value = res.data;
  } else {

    // 电站下全部已绑定的逆变器
    let query = {
      id: electricId.value,
      flag: "0",
    };
    let res = await getDindingInverterS(query);
    inverterList.value = res.data;
  }
}
// 解绑逆变器
const unbound = async (tab: any) => {
  await ElMessageBox.confirm(
    t("licence.Submitjiebang"),
    t("licence.Tips"),
    {
      confirmButtonText: t("licence.gat_jiebang"),
      cancelButtonText: t("licence.cancel"),
      type: "warning",
    }
  )
    .then(async () => {
      let data = {
        lable: tab.lable,
        delFlag: "1",
      };
      await unboundDel(data);
      // 获取逆变器列表
      tabClick(-1, '');
      ElMessage({
        type: "success",
        message: t("licence.gat_success"),
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: t("licence.cancels"),
      });
      // 获取逆变器列表
      tabClick(-1, '');
    });
  tabClick(-1, '');
}
// 删除逆变器
const del = async (tab: any) => {
  await ElMessageBox.confirm(
    t("licence.SubmitDelLable"),
    t("licence.Tips"),
    {
      confirmButtonText: t("licence.del"),
      cancelButtonText: t("licence.cancel"),
      type: "warning",
    }
  )
    .then(async () => {
      let data = {
        lable: tab.lable,
        delFlag: "2",
      };
      await unboundDel(data);
      // 获取逆变器列表
      tabClick(-1, '');
      ElMessage({
        type: "success",
        message: t("licence.use_deletecheng"),
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: t("licence.cancels"),
      });
      // 获取逆变器列表
      tabClick(-1, '');
    });
  tabClick(-1, '');
}
// 删除网关
const delAllInveters = async(gateway:any) => {
      if(typeof gateway == 'undefined')  return
      console.log(gateway.id,'gateway')
      await ElMessageBox.confirm(
        t("licence.DelInverter"),
        t("licence.Tips"),
        {
          confirmButtonText: t("licence.del"),
          cancelButtonText: t("licence.cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          await delAllInveter(gateway.id);
          // 获取逆变器列表
          tabClick(-1, '');
          ElMessage({
            type: "success",
            message: t("licence.use_deletecheng"),
          });
        })
        .catch(() => {
          // 获取逆变器列表
          tabClick(-1, '');
        });
    }
// ==========================================
// 获取网关列表
const getGatewayList = async () => {
  let res = await getGatewayLists(electricId.value);
  GatewayList.value = res.data;
}
// 新增弹框展示
const addShow = () => {
  gatewayForm.value = {
    lable: "",
    gatewayName: "",
  };
  dialogTitle.value = t("licence.gat_addGateway");
  dialogGateway.value = true;
}
// 编辑弹框展示
const editShow = () => {
  dialogTitle.value = t("licence.gat_bianjiGateway");
  gatewayForm.value = gateway.value;
  dialogGateway.value = true;
}
// 弹框新增/编辑网关
const addGateway = async () => {
  let res;
  if (dialogTitle.value == t("licence.gat_bianjiGateway")) {
    let data = {
      id: gateway.value.id,
      lable: gatewayForm.value.lable,
      gatewayName: gatewayForm.value.gatewayName,
    };
    res = await editorGateway(data);
    ElMessage.success(t("licence.powe_bainji"));
    getGatewayList();
  } else {
    let data = {
      stationId: electricId.value,
      lable: gatewayForm.value.lable,
      gatewayName: gatewayForm.value.gatewayName,
    };
    res = await addGateways(data);
    ElMessage.success(t("licence.gat_addChengGong"));
    getGatewayList();
  }

  // if (res.code == "200") {
  //   ElMessage.success(gateway.value ? "编辑成功" : "添加成功");
  // }
  gatewayForm.value = {
    lable: "",
    gatewayName: "",
  };
  dialogGateway.value = false;
  getGatewayList();
}
// 删除网关
const delGateway = async () => {
  await ElMessageBox.confirm(
    t("licence.SubmitDelGateway"),
    t("licence.Tips"),
    {
      confirmButtonText: t("licence.del"),
      cancelButtonText: t("licence.cancel"),
      type: "warning",
    }
  )
    .then(async () => {
      await delGateways({
        id: gateway.value.id,
        lang: lang.value,
      });
      dialogGateway.value = false;
      // 获取网关列表
      getGatewayList();
      ElMessage({
        type: "success",
        message: t("licence.use_deletecheng"),
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: t("licence.cancels"),
      });
      // 获取网关列表
      getGatewayList();
    });
  // 获取网关列表
  getGatewayList();
}
// ===========

// 取消
const resetForm = () => {
  router.go(-1)
}
// 下一步
// const submitForm = ()=>{
//   router.push({
//     path: `/parameter?id=${electricId.value}`,
//   });
// }
// 修改 下一步换成确定
const submitForm = async () => {
  let data = {
    stationId: electricId.value,
  };
  await paramDelivery(data);
  ElMessage.success(t("licence.gat_addChengGong"));
}
    //
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}

// 网关状态颜色
.color1 {
  color: #305add;
}

.color2 {
  color: #f68d2c;
}

.color3 {
  color: #ff2d2d;
}

.color4 {
  color: #82c918;
}

//按钮颜色
.el-button--primary.is-plain {
  color: #305add;
  background: #e7ebfa;
  border-color: #e7ebfa;
}

// 添加设备按钮
.el-button--primary {
  color: #ffffff;
  background-color: #305add;
  border-color: #305add;
}

.content {
  padding: 30px;
}

.conten {
  width: 1200px;
  // height: 700px;
  background: #ffffff;
  border-radius: 6px;
  margin: auto;

  .T-title {
    padding: 20px 30px 30px 20px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    border-bottom: 1px solid #ececec;

    .title-l {
      display: flex;
      cursor: pointer;
      flex-wrap: wrap;
      flex: 1;

      .title-l-s {
        margin-right: 40px;
        font-size: 16px;
        font-weight: 600;
        margin-top: 10px;
      }
    }
  }

  .active {
    color: #305add;
  }

  //   提交 取消按钮
  .Button {
    margin: auto;
    display: table;
    margin-top: 60px;
  }

  //新增编辑网关弹框
  ::v-deep .el-dialog__header {
    border-bottom: 1px solid #ececec;
    text-align: left;
  }

  ::v-deep .el-dialog__title {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #0e1319;
  }

  ::v-deep .el-dialog {
    width: 28%;
    border-radius: 8px;
  }

  ::v-deep .el-form-item__label {
    float: initial;
  }

  ::v-deep .el-input {
    width: 330px;
  }

  //按钮
  .el-button--danger {
    background-color: transparent;
    color: #ff4949;
  }

  // 添加设备弹框样式
  ::v-deep .el-table--border .el-table__cell {
    border-right: none;
  }

  ::v-deep .el-dialog__wrapper {
    top: 200px;
  }
}
.button > *{
  margin-left: 12px;
}
</style>
